package main

import (
	"embed"
	"encoding/base64"
	"image/png"
	"log"
	"os"

	"github.com/kbinani/screenshot"
	"github.com/wailsapp/wails/v3/pkg/application"
	"golang.design/x/hotkey"
	"golang.design/x/hotkey/mainthread"
)

// Wails uses Go's `embed` package to embed the frontend files into the binary.
// Any files in the frontend/dist folder will be embedded into the binary and
// made available to the frontend.
// See https://pkg.go.dev/embed for more information.

//go:embed frontend/dist
var assets embed.FS

// Create a new Wails application by providing the necessary options.
// Variables 'Name' and 'Description' are for application metadata.
// 'Assets' configures the asset server with the 'FS' variable pointing to the frontend files.
// 'Bind' is a list of Go struct instances. The frontend has access to the methods of these instances.
// 'Mac' options tailor the application when running an macOS.
var app = application.New(application.Options{
	Name:        "go-wails3-vue",
	Description: "A demo of using raw HTML & CSS",
	Services: []application.Service{
		application.NewService(&GoService{}),
	},
	Assets: application.AssetOptions{
		Handler: application.AssetFileServerFS(assets),
	},
	Mac: application.MacOptions{
		ApplicationShouldTerminateAfterLastWindowClosed: true,
	},
})

// main function serves as the application's entry point. It initializes the application, creates a window,
// and starts a goroutine that emits a time-based event every second. It subsequently runs the application and
// logs any error that might occur.

var screenShotWindow *application.WebviewWindow

func main() {
	// init registHotkey
	mainthread.Init(registHotkey)
	// Create a new window with the necessary options.
	// 'Title' is the title of the window.
	// 'Mac' options tailor the window when running on macOS.
	// 'BackgroundColour' is the background colour of the window.
	// 'URL' is the URL that will be loaded into the webview.
	screenShotWindow = app.NewWebviewWindowWithOptions(application.WebviewWindowOptions{
		Title: "截图窗口",
		// Mac: application.MacWindow{
		// 	InvisibleTitleBarHeight: 50,
		// 	Backdrop:                application.MacBackdropTranslucent,
		// 	TitleBar:                application.MacTitleBarHiddenInset,
		// },
		BackgroundColour: application.NewRGB(27, 38, 54),
		URL:              "/",
		Hidden:           true,
		Frameless:        true,
		// StartState:       application.WindowStateFullscreen,
	})

	// Create a new menu
	menu := app.NewMenu()
	menu.Add("退出").OnClick(func(ctx *application.Context) {
		app.Quit()
	})

	tray := app.NewSystemTray()
	tray.SetLabel("简截")
	tray.SetMenu(menu)
	tray.OnRightClick(func() {
		tray.OpenMenu()
	})
	tray.OnClick(func() {
		screenShot()
	})

	// Run the application. This blocks until the application has been exited.
	err := app.Run()

	// If an error occurred while running the application, log it and exit.
	if err != nil {
		log.Fatal(err)
	}
}

func registHotkey() {
	hk := hotkey.New([]hotkey.Modifier{hotkey.ModAlt}, hotkey.KeyC)
	err := hk.Register()
	if err != nil {
		log.Fatalf("hotkey: failed to register hotkey: %v", err)
		return
	}

	log.Printf("hotkey: %v is registered\n", hk)
	go getKey(hk)
}

func getKey(hk *hotkey.Hotkey) {
	log.Printf("hotkey: %v is getKey\n", hk)
	for {
		<-hk.Keydown()
		log.Printf("hotkey: %v is down\n", hk)
		screenShot()
	}
}

func screenShot() {

	img, err := screenshot.CaptureDisplay(0)
	if err != nil {
		panic(err)
	}

	file, _ := os.CreateTemp(os.TempDir(), "*.png")
	defer os.Remove(file.Name())
	defer file.Close()
	png.Encode(file, img)
	fileByte, _ := os.ReadFile(file.Name())
	imageBase64 := base64.StdEncoding.EncodeToString(fileByte)
	log.Printf("screenShot success")
	app.EmitEvent("screenShotEvent", imageBase64)
	screenShotWindow.Fullscreen()
	screenShotWindow.Show()
	// n := screenshot.NumActiveDisplays()s
	// for i := 0; i < n; i++ {
	// 	bounds := screenshot.GetDisplayBounds(i)
	// 	img, err := screenshot.CaptureRect(bounds)
	// 	if err != nil {
	// 		panic(err)
	// 	}
	// 	fileName := fmt.Sprintf("%d_%dx%d.png", i, bounds.Dx(), bounds.Dy())
	// 	file, _ := os.Create(fileName)
	// 	defer file.Close()
	// 	png.Encode(file, img)
	// 	fmt.Printf("#%d : %v \"%s\"\n", i, bounds, fileName)
	// }
}
